import config from '../config.js'

export default {
	/**
	 * @description 登录成功后就可以使用如下 key 从缓存中获取
	 * @key token 
	 * @key user
	 */
	login(successCall, failCall, complete) {
		uni.login({
			success: (res) => {
				console.log(res)
				uni.request({
					url: config.baseURL + '/wx/login',
					method: "GET",
					data: {
						code: res.code
					},
					success: (res) => {
						console.log(res.data)
						//保存 token
						uni.setStorageSync('token', res.data.token)
						//保存 user , 因为API限制存储大小
						//所以这里把图片属性去除,获取头像另外直接调用获取即可
						var user = res.data.user
						delete user.avatar
						uni.setStorageSync('user', user)
						if (successCall) successCall(res)
					},
					fail: (res) => {
						console.log(res.data)
						if (failCall) failCall(res)
					}
				})
			},
			fail: (res) => {
				console.log(res.data)
				if (failCall) failCall(res)
			},
			complete() {
				if (complete) complete()
			}
		})
	},
	checkOrSetLogin(successCall, failCall, complete) {
		var token = uni.getStorageSync('token')
		uni.request({
			url: config.baseURL + '/wx/checkLogin',
			method: 'POST',
			header: {
				Authorization: token
			},
			success: (res) => {
				console.log(res.data)
				if (res.data.code == 200) { //有效登录, 这里是来自后端自定义成功的状态码
					if (successCall) successCall(res)
				} else { //无效
					if (failCall) failCall(res)
				}
			},
			fail: (res) => {
				if (failCall) failCall(res)
				if (complete) complete()
			},
			complete() {
				if (complete) complete()
			}
		})
	},
	uploadAvatar(avatar, successCall, failCall) {
		var token = uni.getStorageSync('token')
		uni.uploadFile({
			url: config.baseURL + '/upload/user/avatar',
			filePath: avatar,
			name: 'file',
			header: {
				Authorization: token
			},
			formData: {
				'user': 'avatar'
			},
			success(res) {
				console.log(res)
				if (successCall) successCall(res)
			},
			fail: (res) => {
				console.log(res)
				if (failCall) failCall(res)
			}
		})
	},
	downloadAvatar(successCall, failCall) {
		var token = uni.getStorageSync('token')
		uni.downloadFile({
			url: config.baseURL + '/download/user/avatar',
			header: {
				Authorization: token
			},
			success(res) {
				console.log(res)
				if (res.statusCode == 200) {
					if (successCall) successCall(res)
				}
			},
			fail(res) {
				console.log(res)
				if (failCall) failCall(res)
			}
		})
	},
	changeUserNickname(nickname) {
		var token = uni.getStorageSync('token')
		uni.request({
			url: config.baseURL + '/user/wx/nickname',
			method: 'POST',
			header: {
				Authorization: token
			},
			data: {
				userName: nickname
			},
			success: (res) => {
				console.log(res.data)
			},
			fail: (res) => {
				console.log(res)
			}
		})
	}
};